package pers.vic.third.sms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSONObject;

import pers.vic.base.craw.CrawlConnect;
import pers.vic.base.vo.BooleanWithMsg;
import pers.vic.third.utils.ThirdConfigurationUtils;

/**
 * 利用聚合发送短信验证码.
 * https://www.juhe.cn/docs/api/id/54
 * @author VIC
 *
 */
public class SmsUtils {
	
	private static Logger logger = LoggerFactory.getLogger(SmsUtils.class); 

	private static String key = ThirdConfigurationUtils.getStringValue("juhe.sms.key");

	@Value("${juhe.sms.url}")
	private static String url = ThirdConfigurationUtils.getStringValue("juhe.sms.url");
	
	private static int tplId = ThirdConfigurationUtils.getIntValue("juhe.sms.tpl_id");
	
	
	public static BooleanWithMsg sendSmscode(String mobile, String code) {
		try{
			String text = new CrawlConnect(url)
					.data("key", key)
					.data("mobile", mobile)
					.data("tpl_id", String.valueOf(tplId))
					.data("tpl_value", String.format("#code#=%s", code))
					.getBodyText();
			logger.info("发送短信验证码结果:{}", text);
			JSONObject result = JSONObject.parseObject(text);
			if(result.getInteger("error_code") != 0){
				return BooleanWithMsg.False(result.getString("reason"));
			}
		}catch(Exception e){
			return BooleanWithMsg.False("发送失败");
		}
		return BooleanWithMsg.True();
		
	}
	
	
	public static void main(String[] args) {
		System.out.println(sendSmscode("15056920791", "123456"));
	}
}
